﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace digiMENU
{
    public partial class Form1 : Form
    {
        SqlConnection conn = new SqlConnection("Data Source=Ayush;Initial Catalog=digiMENU;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;
        TextBox tabelNoTextbox;
        string tabelNo="NULL";
        public Form1()
        {
            InitializeComponent();

            setTabel();
        }
        void setTabel()
        {
            Panel tabelPanel = new Panel();
            tabelPanel.BackColor = Color.LightGray;
            tabelPanel.Location = new Point(0, 0);
            tabelPanel.Size = new Size(525, 300);

            Label tabelLabel = new Label(); tabelNoTextbox = new TextBox(); Button enterButton = new Button();

            tabelNoTextbox.Location = new Point(230, 100);
            tabelNoTextbox.Size = new Size(40, 40);
            tabelNoTextbox.TextAlign = HorizontalAlignment.Center;
            setLableProperties(tabelLabel, "Please Enter the Tabel Number ", new Size(300, 30), new Point(140, 50), ContentAlignment.MiddleLeft, Color.LightGray);
            setButtonProperties(enterButton, "enter", "enter", new Size(100, 40), ContentAlignment.MiddleCenter, 9f, Color.DarkOliveGreen, new Point(200, 150));
            enterButton.Click += new EventHandler(enterButtonClick);

            tabelPanel.Controls.Add(enterButton);
            tabelPanel.Controls.Add(tabelNoTextbox);
            tabelPanel.Controls.Add(tabelLabel);

            explorerPanel.AutoScroll = false;
            explorerPanel.Controls.Add(tabelPanel);
        }
        void enterButtonClick(object sender, EventArgs e)
        {
            tabelNo=tabelNoTextbox.Text;
            try { int n = int.Parse(tabelNo); if (n < 1) throw new ArgumentException(); }
            catch (ArgumentException) { MessageBox.Show("The number is invalid!"); return; }
            catch {MessageBox.Show("The number is invalid!"); return;}
            
            cmd.CommandText = "SET IDENTITY_INSERT Tables ON insert into Tables(tableId,totalAmount,pay,callW) values(" + tabelNo + ",0,0,0)";
            cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
            try { reader = cmd.ExecuteReader(); }
            catch { MessageBox.Show("This number has already been taken"); conn.Close(); return; }
            conn.Close();
            showHomePage();
        }
        void showHomePage()
        {
            explorerPanel.Controls.Clear();
            explorerPanel.RowCount = 0;
            goBack.Visible = false;
            banner.Text="Bon Appétit Mexicans";

            cmd.CommandText = "SELECT * FROM Types";
            cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();

            reader = cmd.ExecuteReader();
            for (int i = 1; reader.Read(); ++i) //dynamic buttons generator
            {
                Button dynamicButton = new Button();
                dynamicButton.Click += new EventHandler(dynamicButtonClick);
                setButtonProperties(dynamicButton, reader.GetInt32(0).ToString(), reader.GetString(1), new Size(505, 95), ContentAlignment.MiddleCenter, 24f, Color.Gray, new Point(0, 0));
                explorerPanel.Controls.Add(dynamicButton, i, 0);
            }
            conn.Close();
        }
        void dynamicButtonClick(object sender, EventArgs e)
        {
            Button button = sender as Button;
            itemsPage(button.Text);
        }
        void itemsPage(string name)
        {
            explorerPanel.Controls.Clear();
            explorerPanel.RowCount = 0;
            goBack.Visible = true;
            goBack.Name = "goBack";
            banner.Text = name;

            cmd.CommandText = "SELECT * FROM FoodDrinks JOIN Types ON FoodDrinks.typeId=Types.typeId WHERE Types.name='" + name+"'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn; conn.Open();

            reader = cmd.ExecuteReader();
            for (int i = 1; reader.Read(); ++i) //dynamic buttons generator
            {
                Button dynamicButton = new Button();
                setButtonProperties(dynamicButton, reader.GetInt32(0).ToString(), reader.GetString(1), new Size(505, 80), ContentAlignment.MiddleLeft, 15f, Color.Gray, new Point(0, 0));
                dynamicButton.Click += new EventHandler(infoPage);

                Button selectButton = new Button();
                setButtonProperties(selectButton, dynamicButton.Name, "select", new Size(90, 30), ContentAlignment.MiddleCenter, 12f, Color.DarkOliveGreen, new Point(400, 40));
                selectButton.Click += new EventHandler(selectButtonClick);

                Label priceLable = new Label();
                double price =(double) reader.GetDecimal(3);
                setLableProperties(priceLable, price.ToString(), new Size(90, 30), new Point(400, 10), ContentAlignment.MiddleCenter, Color.LightGray);
               
                dynamicButton.Controls.Add(priceLable);
                dynamicButton.Controls.Add(selectButton);
                explorerPanel.Controls.Add(dynamicButton, i, 0);
            }

            conn.Close();
        }

        protected void infoPage(object sender, EventArgs e)
        {
            Button button = sender as Button;

            explorerPanel.Controls.Clear();
            explorerPanel.RowCount = 0;
            goBack.Name = banner.Text;
            banner.Text = button.Text;

            cmd.CommandText = "SELECT * FROM FoodDrinks WHERE fdId=" + button.Name;
            cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
            reader = cmd.ExecuteReader();
            reader.Read();

            Label info = new Label();
            setLableProperties(info, reader.GetString(2), new Size(510, 400), new Point(0, 0), ContentAlignment.MiddleCenter, Color.LightGray);

            explorerPanel.Controls.Add(info);
            conn.Close();
        }
        double totalAmount; int rowNr; List<string> items = new List<string>();
        void selectButtonClick(object sender, EventArgs e)
        {
            if (payPanel != null)
            {
                actionPanel.Controls.RemoveByKey("payPanel");
            }
            if (orderPlaced)
            {
                actionPanel.Controls.Clear();
                items = new List<string>();
                orderPlaced = false;
                actionPanel.RowCount = 1;
            }
            Button button = sender as Button;
            
            actionPanel.ColumnCount = 3;

            cmd.CommandText = "SELECT * FROM FoodDrinks WHERE fdId="+button.Name;
            cmd.CommandType = CommandType.Text;  cmd.Connection = conn; conn.Open();
            
            reader = cmd.ExecuteReader();
            reader.Read();
            Button placeOrder = null; Label totalAmountLabel = null; rowNr=actionPanel.RowCount;
            if (actionPanel.RowCount != 1)
            {
                --rowNr;
                totalAmountLabel = actionPanel.Controls.Find("total", true)[0] as Label;
                placeOrder = actionPanel.Controls.Find("Place-Order", true)[0] as Button;
            }
            Label name = new Label(), price = new Label(); Button removeButton = new Button();

            setLableProperties(name, reader.GetString(1), new Size(190, 30), new Point(0, 0), ContentAlignment.MiddleLeft, Color.White);
            double cost = (double)reader.GetDecimal(3);
            string fdId = reader.GetSqlInt32(0).ToString();
            string key = fdId + "?" + rowNr.ToString() + "*" + cost.ToString();
            price.Name = name.Name = key;
            
            setLableProperties(price, cost.ToString(), new Size(120, 30), new Point(0, 0), ContentAlignment.MiddleLeft, Color.White);
            setButtonProperties(removeButton, key, "remove", new Size(90, 25), ContentAlignment.TopCenter, 9f, Color.DarkOliveGreen, new Point(0, 0));
            removeButton.Click += new EventHandler(removeButtonClick);

            items.Add(name.Text);
            items.Add(price.Text);
            items.Add(fdId);

            actionPanel.Controls.Add(name);
            actionPanel.Controls.Add(price);
            actionPanel.Controls.Add(removeButton);
            ++actionPanel.RowCount;

            if (actionPanel.RowCount == 2)
            {
                totalAmount = cost;
                totalAmountLabel = new Label();
                totalAmountLabel.Name = "total";
                setLableProperties(totalAmountLabel,"Total = "+ totalAmount.ToString(), new Size(190, 30), new Point(0, 0), ContentAlignment.MiddleLeft, Color.White);
                actionPanel.Controls.Add(totalAmountLabel, 0, actionPanel.RowCount);
                ++actionPanel.RowCount;

                placeOrder = new Button();
                setButtonProperties(placeOrder, "Place-Order", "Place-Order", new Size(100, 30), ContentAlignment.TopCenter, 9f, Color.BurlyWood, new Point(0, 0));
                placeOrder.Click += new EventHandler(orderButtonClick);
                actionPanel.Controls.Add(placeOrder, 1, actionPanel.RowCount+1);
                ++actionPanel.RowCount;
            }
            else
            {
                totalAmount += cost;
                totalAmountLabel.Text ="Total = " + totalAmount.ToString(); 
                actionPanel.Controls.Add(totalAmountLabel, 0, actionPanel.RowCount-1);
                actionPanel.Controls.Add(placeOrder, 1, actionPanel.RowCount);
            }
    
            conn.Close();
      
        }
        void orderButtonClick(object sender, EventArgs e)
        {
            Button yesButton = new Button(), noButton = new Button();
            Label confirmLable = new Label();
            Panel confirmPanel = new Panel();
            actionPanel.AutoScroll = false;
            confirmPanel.BackColor = Color.LightGray;
            confirmPanel.Name = "confirmPanel";
            confirmPanel.Location = new Point(0,0);
            confirmPanel.Size = new Size(530, 198);
           setLableProperties(confirmLable,"please confirm your order !", new Size(300, 30), new Point(160, 30), ContentAlignment.MiddleLeft, Color.LightGray);
           setButtonProperties(yesButton, "yes", "yes", new Size(90, 30), ContentAlignment.TopCenter, 9f, Color.Aqua, new Point(150, 90));
           yesButton.Click += new EventHandler(yesNoButtonClick);
           setButtonProperties(noButton, "no", "no", new Size(90, 30), ContentAlignment.TopCenter, 9f, Color.Aqua, new Point(300, 90));
           noButton.Click += new EventHandler(yesNoButtonClick);
           confirmPanel.Controls.Add(confirmLable);
           confirmPanel.Controls.Add(yesButton);
           confirmPanel.Controls.Add(noButton);
           actionPanel.Controls.Add(confirmPanel,0,0);
        }
        bool orderPlaced = false;
        Panel payPanel = null;
        void yesNoButtonClick(object sender, EventArgs e)
        {
   
            actionPanel.Controls.RemoveByKey("confirmPanel");

            Button button = sender as Button;
            if (button.Name == "yes")
            {
                decimal newAmount = 0;
                for(int i=0;i<items.Count();i+=3)
                {
                  newAmount += decimal.Parse(items[i + 1]);
                  cmd.CommandText = "insert into FoodDrinksOrder values("+items[i+2]+","+tabelNo+")";
                  cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
                  reader = cmd.ExecuteReader();
                  conn.Close();
                }

                cmd.CommandText = "select totalAmount from Tables where tableId =" + tabelNo;
                cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
                reader = cmd.ExecuteReader();
                reader.Read();
                newAmount += reader.GetDecimal(0);
                conn.Close();

                cmd.CommandText = "update Tables set totalAmount =" + newAmount.ToString() + " where tableId =" + tabelNo;
                cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
                reader = cmd.ExecuteReader();
                conn.Close();

                orderPlaced = true;

                Button showListButton = new Button(), payButton = new Button();
                Label infoLable = new Label();
                payPanel = new Panel();
                actionPanel.AutoScroll = false;
                payPanel.BackColor = Color.LightGray;
                payPanel.Name = "payPanel";
                payPanel.Location = new Point(0, 0);
                payPanel.Size = new Size(530, 198);
                setLableProperties(infoLable, "Your order is being prepaired, Please wait for a while", new Size(500, 30), new Point(50, 30), ContentAlignment.MiddleLeft, Color.LightGray);
                setButtonProperties(showListButton, "showList", "show list", new Size(90, 30), ContentAlignment.TopCenter, 9f, Color.Aqua, new Point(150, 90));
                showListButton.Click += new EventHandler(showListButtonClick);
                setButtonProperties(payButton, "pay", "pay", new Size(90, 30), ContentAlignment.TopCenter, 9f, Color.Aqua, new Point(300, 90));
                payButton.Click += new EventHandler(payButtonClick);
                payPanel.Controls.Add(infoLable);
                payPanel.Controls.Add(showListButton);
                payPanel.Controls.Add(payButton);
                actionPanel.Controls.Add(payPanel, 0, 0);
            }
        }
        void payButtonClick(object sender, EventArgs e)
        {
            actionPanel.Controls.Clear();
            actionPanel.RowCount = 1;
            payPanel = null;
            
            showHomePage();

            cmd.CommandText = "update Tables set pay=1 where tableId =" + tabelNo;
            cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
            reader = cmd.ExecuteReader();
            conn.Close();
        }
        
        void showListButtonClick(object sender, EventArgs e)
        {
            Button button = sender as Button;
            if (button.Text == "hide list")
            {
                if (banner.Text == "Bon Appétit Mexicans")
                    showHomePage();
                else
                    itemsPage(banner.Text);

                button.Text = "show list";
            }
            else
            {
                goBack.Visible = false;
                button.Text = "hide list";
                explorerPanel.Controls.Clear();

                if (items.Count == 0) return;
                Label totalAmountLabel = totalAmountLabel = new Label();
                   
                int i; double total = 0;
                for (i = 0; i < items.Count(); i += 3)
                {
                    Label info = new Label();
                    total += Double.Parse(items[i + 1]);
                    setLableProperties(info, items[i] + " " + items[i + 1], new Size(300, 30), new Point(0, 0), ContentAlignment.MiddleLeft, Color.White);
                    explorerPanel.Controls.Add(info, 0, i);
                }
                setLableProperties(totalAmountLabel, "Total = " + total.ToString(), new Size(190, 30), new Point(0, 0), ContentAlignment.MiddleLeft, Color.White);
                    
                explorerPanel.Controls.Add(totalAmountLabel, 0, i + 1);
                
            }
        }
        void removeButtonClick(object sender, EventArgs e)
        {
            Button button = sender as Button; 

            int c=3; char[] delim=new char[]{'?','*'}; string[] sub = new string[c];

            sub = button.Name.Split(delim, c);

            actionPanel.Controls.RemoveByKey(button.Name);
            actionPanel.Controls.RemoveByKey(button.Name);
            actionPanel.Controls.RemoveByKey(button.Name);
            for (int i = 0; i < items.Count();i+=3)
            {
                if(items[i+2]==sub[0])
                {   
                    items.RemoveAt(i);
                    items.RemoveAt(i);
                    items.RemoveAt(i);
                    break;
                }
            }
            --actionPanel.RowCount;
      
            

            Label totalAmountLabel = null;
            totalAmountLabel = actionPanel.Controls.Find("total", true)[0] as Label;
     
            totalAmount -= Double.Parse(sub[2]);
            totalAmountLabel.Text = "Total = " + totalAmount.ToString();
            actionPanel.Controls.Add(totalAmountLabel, 0, actionPanel.RowCount-1);

            if (actionPanel.Controls.Count == 2)
            {
                actionPanel.Controls.Clear();
                actionPanel.RowCount = 1;

                if(payPanel!=null)actionPanel.Controls.Add(payPanel);
            }
        }
        void setLableProperties(Label priceLable,string text,Size size,Point point,ContentAlignment aline,Color color)
        {
            priceLable.Text = text;
            priceLable.BackColor = color;
            priceLable.FlatStyle = FlatStyle.Flat;
            priceLable.TextAlign = aline;
            priceLable.Location = point;
            priceLable.Font = new Font("Kristen ITC", 12f);
            priceLable.Size = size;
        }
        void setButtonProperties(Button dynamicButton,string id,string text,Size size, ContentAlignment align, float size2,Color color,Point point)
        {
            dynamicButton.Name = id;
            dynamicButton.Text = text;
            dynamicButton.Size = size;
            dynamicButton.Location = point;
            dynamicButton.TextAlign = align;
            dynamicButton.BackColor = color;
            dynamicButton.FlatStyle = FlatStyle.Flat;
            dynamicButton.FlatAppearance.BorderColor = Color.Black;
            dynamicButton.FlatAppearance.BorderSize = 2;
            dynamicButton.Font = new Font("Kristen ITC", size2);
        }

        private void goBack_Click(object sender, EventArgs e)
        {
            if (goBack.Name == "goBack")
                showHomePage();
            else
                itemsPage(goBack.Name);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (tabelNo != "NULL")
            {
                cmd.CommandText = "delete from Tables where tableId =" + tabelNo;
                cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
                reader = cmd.ExecuteReader();
                conn.Close();
            }
        }

        private void callWaitressButton_Click(object sender, EventArgs e)
        {
            cmd.CommandText = "update Tables set callW=1 where tableId =" + tabelNo;
            cmd.CommandType = CommandType.Text; cmd.Connection = conn; conn.Open();
            reader = cmd.ExecuteReader();
            conn.Close();
        }
        
    }
}
